import switch_control.telnetAPI as telnetAPI
import gpu_port_ip_map as Port_ip_map
import time
import argparse



def publish_acl_no_small_clos():
    host_ip = '10.174.216.35'
    username = 'admin1234'
    password = 'Oxc_2012'
    changepwd = 'N'

    commands = []
    commit = 'commit'
    quit = 'q'
    sy = "system-view"
    admin = "admin"
    port_mode = "port-mode port"
    confirm = "Y"
    acl_id = 410
    acl_to_publish = {}
    #acl_to_publish["vs1"] = [("192.168.6.3", None, "100GE1/0/49", "100GE1/0/1", "410"), ("192.168.7.3", None, "100GE1/0/50", "100GE1/0/2", "411")]
    acl_to_publish["vs1"] = []
    for i in range(32):
        src_ip = Port_ip_map.find_gpu_ip(32+i)
        dst_ip = None
        outport_ip = Port_ip_map.find_spine_ip(32+i)
        inport_name = Port_ip_map.find_hw_leaf_port(i)
        acl_to_publish["vs1"].append((src_ip, dst_ip, outport_ip, inport_name, acl_id))
        acl_id += 1

    for vs_name in acl_to_publish.keys():
        commands.append(sy)

        for entry in acl_to_publish[vs_name]:
            mark = entry[-1]
            src__ip = entry[0]
            dst_ip = entry[1]
            interface = entry[2]
            start_port = entry[3]

            commands.append("interface %s" % start_port)
            commands.append("acl number 3%s" % mark)
            cmd = "rule permit ip "
            if src__ip != None:
                cmd += ("source %s 0" % src__ip)
            if dst_ip != None:
                cmd += ("destination %s 0" % dst_ip)
            commands.append(cmd)
            commands.append(commit)
            commands.append(quit)

            commands.append("interface %s" % start_port)
            commands.append("traffic classifier c%s" % mark)
            commands.append("if-match acl 3%s" %mark)
            commands.append(commit)
            commands.append(quit)

            commands.append("interface %s" % start_port)
            commands.append("traffic behavior b%s" % mark)
            commands.append("redirect nexthop %s" %interface)
            commands.append(commit)
            commands.append(quit)

            commands.append("interface %s" % start_port)
            commands.append("traffic policy p%s" % mark)
            commands.append("classifier c%s behavior b%s" %(mark, mark))
            commands.append(commit)
            commands.append(quit)

            commands.append("interface %s" % start_port)
            commands.append("traffic-policy p%s inbound" % mark)
            commands.append(commit)
        commands.append(quit)
        
    telnet_client = telnetAPI.TelnetClient()
    if telnet_client.login_host(host_ip, username, password, changepwd):
        for cmd in commands:
            telnet_client.execute_some_command(cmd, interval=0.1)
    else:
        print("fail")
        time.sleep(3)

if __name__ == "__main__":
    publish_acl_no_small_clos()


